package com.innovation.ic.sc.base.service.sc.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.innovation.ic.b1b.framework.util.HttpUtils;
import com.innovation.ic.b1b.framework.util.StringUtils;
import com.innovation.ic.sc.base.mapper.sc.MyCompanyMapper;
import com.innovation.ic.sc.base.model.sc.*;
import com.innovation.ic.sc.base.pojo.constant.Constants;
import com.innovation.ic.sc.base.pojo.constant.handler.RabbitMqConstants;
import com.innovation.ic.sc.base.pojo.enums.*;
import com.innovation.ic.sc.base.pojo.variable.*;
import com.innovation.ic.sc.base.service.ServiceHelper;
import com.innovation.ic.sc.base.service.sc.*;
import com.innovation.ic.sc.base.service.sc_data.InitMyCompanyService;
import com.innovation.ic.sc.base.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@Service
@Slf4j
public class MyCompanyServiceImpl extends ServiceImpl<MyCompanyMapper, MyCompany> implements MyCompanyService {

    @Resource
    private UploadFileService uploadFileService;

    @Resource
    private ErpMyCompanyNameService erpMyCompanyNameService;

    @Resource
    private DictionariesService dictionariesService;

    @Resource
    private ServiceHelper serviceHelper;

    @Resource
    private InitMyCompanyService initMyCompanyService;

    @Resource
    private MyCompanyCurrencyService myCompanyCurrencyService;

    @Resource
    private MyCompanyService myCompanyService;

    @Resource
    private MyCompanyEnterpriseService myCompanyEnterpriseService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServiceResult registerCompany(MyCompanyVo myCompanyVo) throws IOException {
        ServiceResult serviceResult = new ServiceResult();
        Boolean update = myCompanyVo.getUpdate().equals(Boolean.TRUE) ? Boolean.TRUE : Boolean.FALSE;
        MyCompany existsMyCompany = myCompanyService.findByName(myCompanyVo.getName());
        if (update) {
            if (existsMyCompany != null) {
                Integer id = existsMyCompany.getId();
                List<MyCompanyEnterprise> myCompanyEnterpriseList = myCompanyEnterpriseService.findByMyCompanyId(id);
                for (MyCompanyEnterprise myCompanyEnterprise : myCompanyEnterpriseList) {
                    this.deactivateMyCompany(myCompanyEnterprise.getId());
                }
                this.baseMapper.deleteById(id);
                existsMyCompany = null;
            }
        }


        //查看当前公司,是否处在正在审核状态
        Integer state = serviceHelper.getMyCompanyEnterpriseMapper().containCompanyNameState(myCompanyVo);
        if (AuditStatusEnum.PENDING.getErpStatusCode().equals(state)) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("该公司正在审核，请勿重复添加");
            return serviceResult;
        }
        //校验公司,是否重复添加
        Integer associationExistsCount = serviceHelper.getMyCompanyEnterpriseMapper().checkRegistrationCompany(myCompanyVo);
        if (associationExistsCount > 0) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("该公司已与我方建立关系");
            return serviceResult;
        }
        Integer containCompanyNameCount = serviceHelper.getMyCompanyEnterpriseMapper().containCompanyNameCount(myCompanyVo);
        if (containCompanyNameCount > 0) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("该供应商已开通账号，无法新增");
            return serviceResult;
        }
        //查看erp是否有公司
        Map<String, Object> existsErpParamMap = new HashMap<>();
        existsErpParamMap.put("name", myCompanyVo.getName());
        ErpMyCompanyName existsErpMyCompanyName = erpMyCompanyNameService.findByNameMap(existsErpParamMap);

        //判断当前人是否添加本公司
        if (existsErpMyCompanyName != null && existsErpMyCompanyName.getExternalId().equals(myCompanyVo.getEnterpriseId())) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("无法添加本身供应商");
            return serviceResult;
        }
        //默认为审核通过
        Integer myCompanyId = null;
        if (existsMyCompany == null) {
            //创建我的公司id
            myCompanyId = this.saveMyCompany(myCompanyVo, existsErpMyCompanyName);
        } else {
            //有直接建立关联
            myCompanyId = existsMyCompany.getId();
        }
        myCompanyVo.setId(myCompanyId);
        //发送给erp注册公司
        this.sendRegisterCompany(myCompanyVo);

        //建立关联
        MyCompanyEnterprise myCompanyEnterprise = new MyCompanyEnterprise();
        myCompanyEnterprise.setEnterpriseId(myCompanyVo.getEnterpriseId());
        myCompanyEnterprise.setState(MyCompanyEnum.TO_BE_REVIEWED.getCode());
        myCompanyEnterprise.setMyCompanyId(myCompanyId);
        myCompanyEnterprise.setCreatorId(myCompanyVo.getCreatorId());
        myCompanyEnterprise.setCreateDate(new Date());
        myCompanyEnterprise.setMainCompany(MyCompanyEnterpriseEnum.NO_ACCORD_WITH.getCode());
        serviceHelper.getMyCompanyEnterpriseMapper().insert(myCompanyEnterprise);
        //更新关联id
        //保存图片
        List<UploadFileVo> uploadFileVo = myCompanyVo.getUploadFileVo();
        if (!CollectionUtils.isEmpty(uploadFileVo)) {
            for (UploadFileVo fileVo : uploadFileVo) {
                uploadFileService.updateRelationIdAndType(fileVo.getId().toString(), UploadFileEnum.MY_COMPANY, myCompanyEnterprise.getId(), fileVo.getCustomType());
            }
        }
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }


    /**
     * 需要添加我的公司
     *
     * @param myCompanyVo
     * @return
     */
    private Integer saveMyCompany(MyCompanyVo myCompanyVo, ErpMyCompanyName existsErpMyCompanyName) {
        //添加MyCompany表
        MyCompany myCompany = new MyCompany();
        BeanUtils.copyProperties(myCompanyVo, myCompany);
        //新增的时候为空
        //myCompany.setEnterpriseId(null);
        //默认待审核
        myCompany.setCreateDate(new Date());
        myCompany.setCreatorId(myCompanyVo.getCreatorId());
        if (existsErpMyCompanyName != null && StringUtils.validateParameter(existsErpMyCompanyName.getExternalId())) {
            myCompany.setEnterpriseId(existsErpMyCompanyName.getExternalId());
        }
        this.baseMapper.insertRetuenId(myCompany);
        //存入redis
        initMyCompanyService.savaRedistMyCompany(myCompany);
        return myCompany.getId();
    }


    private void sendScsMyCompanyEnterpriseMessage(MyCompanyEnterprise myCompanyEnterprise, MyCompanyScsEnum myCompanyScsEnum, String queueName) throws IOException {
        MyCompany myCompany = this.baseMapper.selectById(myCompanyEnterprise.getMyCompanyId());
        MyCompanyScsMessagePojo myCompanyMessagePojo = new MyCompanyScsMessagePojo();
        myCompanyMessagePojo.setCreatorId(myCompanyEnterprise.getCreatorId());
        myCompanyMessagePojo.setType(myCompanyScsEnum.getCode());
        myCompanyMessagePojo.setEnterpriseId(myCompanyEnterprise.getEnterpriseId());
        myCompanyMessagePojo.setRelationEnterpriseId(myCompany.getEnterpriseId());
        JSONObject json = (JSONObject) JSONObject.toJSON(myCompanyMessagePojo);
        // 包装发送到rabbitmq的消息内容
        JSONObject result = serviceHelper.packageSendRabbitMqMsgData(json, queueName);
        log.info("推送给 scs rabbitmq的交换机:[{}],队列:[{}]的消息内容为:[{}]", RabbitMqConstants.SC_ERP_EXCHANGE, queueName, result.toString());
        serviceHelper.getRabbitMqManager().basicPublish(RabbitMqConstants.SC_ERP_EXCHANGE, queueName, null, result.toString().getBytes());
    }


    /**
     * 绑定参数关联
     *
     * @param myCompanyAddRelation
     * @return
     */
    private Map<String, Object> bindMyCompanyAddRelation(MyCompanyAddRelation myCompanyAddRelation) {
        Map<String, Object> param = new HashMap<>();
        param.put("ID", myCompanyAddRelation.getId());
        param.put("SubID", myCompanyAddRelation.getSubId());
        param.put("Creator", myCompanyAddRelation.getCreator());
        param.put("Files", myCompanyAddRelation.getFiles());
        return param;
    }

    @Override
    public ServiceResult<MyCompanyPojo> getDetail(Integer id) {
        ServiceResult<MyCompanyPojo> serviceResult = new ServiceResult();
        if (id == null) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("id不能为空");
            return serviceResult;
        }
        //查询数据库
        MyCompany myCompany = this.baseMapper.selectById(id);
        if (myCompany == null) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("查询为空");
            return serviceResult;
        }
        //封装返回对象
        MyCompanyPojo myCompanyPojo = new MyCompanyPojo();
        myCompanyPojo.setEnterpriseId(myCompany.getEnterpriseId());
        myCompanyPojo.setId(myCompany.getId());
        myCompanyPojo.setName(myCompany.getName());
        List<String> dictionariesIds = new ArrayList<>();
        dictionariesIds.add(myCompany.getCountryRegionId());
        dictionariesIds.add(myCompany.getCompanyTypeId());
        dictionariesIds.add(myCompany.getInvoicTypeId());
        dictionariesIds.add(myCompany.getCurrencyId());
        ServiceResult<List<Dictionaries>> serviceResultDictionaries = dictionariesService.findByIds(dictionariesIds);
        Map<String, String> dictionariesMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(serviceResultDictionaries.getResult())) {
            for (Dictionaries dictionaries : serviceResultDictionaries.getResult()) {
                dictionariesMap.put(dictionaries.getId(), dictionaries.getDName());
            }
        }
        myCompanyPojo.setCompanyType(dictionariesMap.get(myCompany.getCompanyTypeId()));
        myCompanyPojo.setCountryRegion(dictionariesMap.get(myCompany.getCountryRegionId()));
        myCompanyPojo.setInvoicType(dictionariesMap.get(myCompany.getInvoicTypeId()));
        //查询文件表
        ServiceResult<List<UploadFile>> relationIdList = uploadFileService.findByRelationId(UploadFileEnum.MY_COMPANY, id.toString());
        List<UploadFile> relationIdListResult = relationIdList.getResult();
        List<UploadFilePojo> uploadFilePojoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(relationIdListResult)) {
            for (UploadFile uploadFile : relationIdListResult) {
                UploadFilePojo uploadFilePojo = new UploadFilePojo();
                BeanUtils.copyProperties(uploadFile, uploadFilePojo);
                uploadFilePojoList.add(uploadFilePojo);
            }
        }
        myCompanyPojo.setFiles(uploadFilePojoList);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage("查询成功");
        serviceResult.setResult(myCompanyPojo);
        return serviceResult;
    }

    @Override
    public ServiceResult delete(String ids) {
        ServiceResult serviceResult = new ServiceResult();
        //请求url
        String deleteUrl = serviceHelper.getMyCompanyConfig().getErpServiceUrl() + serviceHelper.getMyCompanyConfig().getDelete();
        String result = HttpUtils.sendPostJson(deleteUrl, Arrays.asList(ids.split(",")));
        if (!StringUtils.validateParameter(result)) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("调用接口返回为空");
            return serviceResult;
        }
        JSONObject searchCompanyUrlData = JSONObject.parseObject(result);
        if (!"200".equals(searchCompanyUrlData.get("status") + "") || !"true".equals(searchCompanyUrlData.get("success") + "")) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage(searchCompanyUrlData.get("msg") + "");
            return serviceResult;
        }
        serviceResult.setSuccess(Boolean.parseBoolean(searchCompanyUrlData.get("success") + ""));
        serviceResult.setMessage("查询成功");
        serviceResult.setResult(searchCompanyUrlData.get("Data"));
        return serviceResult;
    }


    @Override
    public ServiceResult checkRegistrationCompany(MyCompanyVo myCompanyVo) {
        ServiceResult serviceResult = new ServiceResult<>();
        //查看当前公司,是否处在正在审核状态
        Integer state = serviceHelper.getMyCompanyEnterpriseMapper().containCompanyNameState(myCompanyVo);
        if (AuditStatusEnum.PENDING.getErpStatusCode().equals(state)) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("该公司正在审核，请勿重复添加");
            return serviceResult;
        }
        //校验公司,是否重复添加
        Integer associationExistsCount = serviceHelper.getMyCompanyEnterpriseMapper().checkRegistrationCompany(myCompanyVo);
        if (associationExistsCount > 0) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("该公司已与我方建立关系");
            return serviceResult;
        }
        Integer containCompanyNameCount = serviceHelper.getMyCompanyEnterpriseMapper().containCompanyNameCount(myCompanyVo);
        if (containCompanyNameCount > 0) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("该供应商已开通账号，无法新增");
            return serviceResult;
        }
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    @Override
    public ServiceResult<PageInfo<MyCompanyPojo>> findByMyCompany(SearchCompanyVo searchCompanyVo) {
        ServiceResult<PageInfo<MyCompanyPojo>> serviceResult = new ServiceResult();
        PageHelper.startPage(searchCompanyVo.getPage(), searchCompanyVo.getPageSize());
        List<MyCompanyPojo> list = this.baseMapper.findByMyCompanyPage(searchCompanyVo);

        List<String> paramList = new ArrayList<>();
        paramList.add(MyCompanyDictionariesEnum.INVOICE_TYPE.getcName());
        paramList.add(MyCompanyDictionariesEnum.COUNTRY_AND_REGION.getcName());
        List<Dictionaries> dictionaries = dictionariesService.findByDcodes(paramList);
        List<MyCompanyCurrency> myCompanyCurrencyList = myCompanyCurrencyService.findAll();
        for (MyCompanyPojo myCompanyPojo : list) {
            for (Dictionaries dictionary : dictionaries) {
                for (MyCompanyCurrency myCompanyCurrency : myCompanyCurrencyList) {
                    if (myCompanyCurrency.getId().toString().equals(myCompanyPojo.getCurrencyId())) {
                        myCompanyPojo.setCurrencyName(myCompanyCurrency.getName());
                    }
                }
                if (dictionary.getId().equals(myCompanyPojo.getInvoicType())) {
                    myCompanyPojo.setInvoicTypeName(dictionary.getDName());
                }
                if (dictionary.getId().equals(myCompanyPojo.getCountryRegion())) {
                    myCompanyPojo.setCountryRegionName(dictionary.getDName());
                }
            }
            if (StringUtils.validateParameter(myCompanyPojo.getName()) && myCompanyPojo.getName().equals(searchCompanyVo.getEnterpriseName())) {
                myCompanyPojo.setMainCompany(MyCompanyEnterpriseEnum.ACCORD_WITH.getCode());
            }
        }
        PageInfo<MyCompanyPojo> pageInfo = new PageInfo<>(list);
        serviceResult.setResult(pageInfo);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    @Override
    public ServiceResult deactivateMyCompany(Integer relationEnterpriseId) throws IOException {
        ServiceResult serviceResult = new ServiceResult();
        if (relationEnterpriseId == null) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("id不能为空");
            return serviceResult;
        }
        MyCompanyEnterprise myCompanyEnterprise = serviceHelper.getMyCompanyEnterpriseMapper().selectById(relationEnterpriseId);
        if (myCompanyEnterprise.getMainCompany().equals(MyCompanyEnterpriseEnum.ACCORD_WITH.getCode())) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("主公司不能删除");
            return serviceResult;
        }
        serviceHelper.getMyCompanyEnterpriseMapper().deleteById(relationEnterpriseId);
        //发送给erp
        this.sendDeactivateMyCompanyMessage(myCompanyEnterprise);
        //发送给scs
        this.sendScsMyCompanyEnterpriseMessage(myCompanyEnterprise, MyCompanyScsEnum.DELETE, RabbitMqConstants.SC_ERP_DEL_RELATION_COMPANY_QUEUE);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage("停用成功");
        return serviceResult;
    }

    private void sendDeactivateMyCompanyMessage(MyCompanyEnterprise myCompanyEnterprise) throws IOException {
        MyCompany myCompany = this.baseMapper.selectById(myCompanyEnterprise.getMyCompanyId());
        MyCompanyMessagePojo myCompanyMessagePojo = new MyCompanyMessagePojo();
        myCompanyMessagePojo.setID(myCompanyEnterprise.getEnterpriseId());
        myCompanyMessagePojo.setSubID(myCompany.getEnterpriseId());
        JSONObject json = (JSONObject) JSONObject.toJSON(myCompanyMessagePojo);
        // 包装发送到rabbitmq的消息内容
        JSONObject result = serviceHelper.packageSendRabbitMqMsgData(json, RabbitMqConstants.SC_ERP_DELETE_COMPANY);
        log.info("推送给 erp rabbitmq删除我的公司关联关系 消息,交换机:[{}],队列:[{}] , key:[{}] ,的消息内容为:[{}]  ", RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_TO_ERP_CRM_QUEUE_NAME, RabbitMqConstants.SC_ERP_DELETE_COMPANY, result.toString());
        serviceHelper.getRabbitMqManager().basicPublish(RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_TO_ERP_CRM_QUEUE_NAME, RabbitMqConstants.SC_ERP_DELETE_COMPANY, null, result.toString().getBytes());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void relationMyCompanyNameVo(RelationMyCompanyNameVo relationMyCompanyNameVo) throws IOException {
        if (!StringUtils.validateParameter(relationMyCompanyNameVo.getID())) {
            return;
        }
        if (!StringUtils.validateParameter(relationMyCompanyNameVo.getSubID())) {
            return;
        }
        //查询已经保存的公司
        ErpMyCompanyName erpMyCompanyName = erpMyCompanyNameService.findByExternalId(relationMyCompanyNameVo.getSubID());
        if (erpMyCompanyName == null) {
            return;
        }
        //校验公司,已经添加,查看是否已经添加公司
        Integer count = this.baseMapper.checkRegistrationCompanyId(relationMyCompanyNameVo);
        if (count > 0) {
            return;
        }
        //查看是否需要添加公司表
        MyCompany containMyCompany = this.baseMapper.findByName(erpMyCompanyName.getName());
        MyCompany myCompany = new MyCompany();
        if (containMyCompany == null) {
            myCompany.setEnterpriseId(relationMyCompanyNameVo.getSubID());
            myCompany.setCreatorId(relationMyCompanyNameVo.getCreator());
            myCompany.setCountryRegionId(erpMyCompanyName.getDistrict());
            myCompany.setCompanyTypeId(erpMyCompanyName.getSupplierType());
            myCompany.setInvoicTypeId(erpMyCompanyName.getInvoiceType());
            myCompany.setName(erpMyCompanyName.getName());
            //审核消息添加收款信息
            myCompany.setBookAccountId(relationMyCompanyNameVo.getBookAccountID());
            myCompany.setReceivingCompany(relationMyCompanyNameVo.getTitle());
            myCompany.setBankOfDeposit(relationMyCompanyNameVo.getBank());
            myCompany.setAccountNumber(relationMyCompanyNameVo.getAccount());
            myCompany.setBankAddress(relationMyCompanyNameVo.getBankAddress());
            myCompany.setCreatorId(relationMyCompanyNameVo.getCreator());
            myCompany.setErpReceive(1);
            myCompany.setCurrencyId(relationMyCompanyNameVo.getCurrency());
            //同时解析json文件
            this.baseMapper.insertRetuenId(myCompany);
            //存入redis
            initMyCompanyService.savaRedistMyCompany(myCompany);
        } else {
            myCompany.setId(containMyCompany.getId());
            //更新最新收款信息,判空
            if (!StringUtils.isEmpty(relationMyCompanyNameVo.getBookAccountID())) {
                UpdateWrapper<MyCompany> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("id", myCompany.getId());
                updateWrapper.set("book_account_id", relationMyCompanyNameVo.getBookAccountID());
                updateWrapper.set("receiving_company", relationMyCompanyNameVo.getTitle());
                updateWrapper.set("bank_of_deposit", relationMyCompanyNameVo.getBank());
                updateWrapper.set("account_number", relationMyCompanyNameVo.getAccount());
                updateWrapper.set("bank_address", relationMyCompanyNameVo.getBankAddress());
                updateWrapper.set("swift_code", relationMyCompanyNameVo.getSwiftCode());
                updateWrapper.set("currency_id", relationMyCompanyNameVo.getCurrency());
                this.baseMapper.update(null, updateWrapper);
            }
        }
        relationMyCompanyNameVo.setMyCompanyId(myCompany.getId().toString());

        //添加关联表
        MyCompanyEnterprise myCompanyEnterprise = new MyCompanyEnterprise();
        myCompanyEnterprise.setEnterpriseId(relationMyCompanyNameVo.getID());
        myCompanyEnterprise.setState(relationMyCompanyNameVo.getStatus());
        myCompanyEnterprise.setMyCompanyId(myCompany.getId());
        myCompanyEnterprise.setCreateDate(new Date());
        myCompanyEnterprise.setCause(relationMyCompanyNameVo.getSummary());
        //默认待审核
        myCompanyEnterprise.setState(MyCompanyEnum.TO_BE_REVIEWED.getCode());
        myCompanyEnterprise.setMainCompany(MyCompanyEnterpriseEnum.NO_ACCORD_WITH.getCode());
        serviceHelper.getMyCompanyEnterpriseMapper().insert(myCompanyEnterprise);


        if (StringUtils.validateParameter(relationMyCompanyNameVo.getFiles())) {
            relationMyCompanyNameVo.setID(myCompanyEnterprise.getId().toString());
            Object filesParse = JSONObject.parse(relationMyCompanyNameVo.getFiles());
            if (filesParse == null) {
                return;
            }
            List<FileVo> list = new ArrayList<>();
            JSONArray jsonArray = (JSONArray) filesParse;
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject dataBean = (JSONObject) jsonArray.get(i);
                FileVo fileVo = new FileVo();
                String fileName = dataBean.getString("FileName");
                String url = dataBean.getString("Url");
                fileVo.setFileName(fileName);
                //下载图片，转换连接
                String downloadPicture = downloadPicture(url, fileName);
                if (!StringUtils.validateParameter(downloadPicture)) {
                    continue;
                }
                fileVo.setUrl(downloadPicture);
                list.add(fileVo);
            }
            uploadFileService.saveRelationMyCompanyBatch(list, relationMyCompanyNameVo);
        }
        //推送消息给scs
        this.sendScsMyCompanyEnterpriseMessage(myCompanyEnterprise, MyCompanyScsEnum.ADD, RabbitMqConstants.SC_ERP_ADD_RELATION_COMPANY_QUEUE);
    }

    @Override
    public void listenAuditErpCompany(RelationMyCompanyNameVo relationMyCompanyNameVo) throws IOException {
        //找到sc公司表
        MyCompany myCompany = this.baseMapper.findByEnterpriseId(relationMyCompanyNameVo.getSubID());
        if (myCompany == null) {
            return;
        }
        UpdateWrapper<MyCompanyEnterprise> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("my_company_id", myCompany.getId());
        updateWrapper.eq("enterprise_id", relationMyCompanyNameVo.getID());
        updateWrapper.set("state", relationMyCompanyNameVo.getStatus());
        updateWrapper.set("cause", relationMyCompanyNameVo.getSummary());
        serviceHelper.getMyCompanyEnterpriseMapper().update(null, updateWrapper);
        if (MyCompanyEnum.ADOPT.getCode().equals(relationMyCompanyNameVo.getStatus())) {
            //审核通过,推送消息给scs
            MyCompanyEnterprise myCompanyEnterprise = new MyCompanyEnterprise();
            myCompanyEnterprise.setEnterpriseId(relationMyCompanyNameVo.getID());
            myCompanyEnterprise.setMyCompanyId(myCompany.getId());
            this.sendScsMyCompanyEnterpriseMessage(myCompanyEnterprise, MyCompanyScsEnum.ADD, RabbitMqConstants.SC_ERP_ADD_RELATION_COMPANY_QUEUE);
        }
    }


    @Override
    public void listenDeleteErpCompany(RelationMyCompanyNameVo relationMyCompanyNameVo) throws IOException {
        //删除关联关系
        if (!StringUtils.validateParameter(relationMyCompanyNameVo.getID()) || !StringUtils.validateParameter(relationMyCompanyNameVo.getSubID())) {
            return;
        }
        //公司名字加关联id
        MyCompany myCompany = this.baseMapper.findByEnterpriseId(relationMyCompanyNameVo.getSubID());
        if (myCompany == null) {
            return;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("enterprise_id", relationMyCompanyNameVo.getID());
        param.put("my_company_id", myCompany.getId());
        serviceHelper.getMyCompanyEnterpriseMapper().deleteByMap(param);
        //同时发送消息给他scs
        MyCompanyEnterprise myCompanyEnterprise = new MyCompanyEnterprise();
        myCompanyEnterprise.setMyCompanyId(myCompany.getId());
        myCompanyEnterprise.setEnterpriseId(relationMyCompanyNameVo.getID());
        this.sendScsMyCompanyEnterpriseMessage(myCompanyEnterprise, MyCompanyScsEnum.DELETE, RabbitMqConstants.SC_ERP_DEL_RELATION_COMPANY_QUEUE);
    }

    @Override
    public void addUserRelation(User userdata) {
        if (userdata == null) {
            return;
        }
        //主账号才走逻辑
        if (!StringUtils.isEmpty(userdata.getFatherId())) {
            return;
        }
        String enterpriseId = userdata.getEnterpriseId();
        //查询erp是否包含
        ErpMyCompanyName erpMyCompanyName = erpMyCompanyNameService.findByExternalId(enterpriseId);
        if (erpMyCompanyName == null) {
            log.error("添加主账号和公司关联, addUserRelation erpMyCompanyName 返回为空");
            return;
        }
        //查看id是否已经存在
        MyCompany containMyCompany = this.baseMapper.findByEnterpriseId(enterpriseId);
        Integer myCompanyId = null;
        if (containMyCompany == null) {
            MyCompany myCompany = new MyCompany();
            myCompany.setName(erpMyCompanyName.getName());
            myCompany.setCreateDate(new Date());
            myCompany.setEnterpriseId(erpMyCompanyName.getExternalId());
            myCompany.setCountryRegionId(erpMyCompanyName.getDistrict());
            myCompany.setCompanyTypeId(erpMyCompanyName.getSupplierType());
            myCompany.setInvoicTypeId(erpMyCompanyName.getInvoiceType());
            this.baseMapper.insertRetuenId(myCompany);
            myCompanyId = myCompany.getId();
        } else {
            myCompanyId = containMyCompany.getId();
        }
        //关联判重
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("my_company_id", myCompanyId);
        paramMap.put("enterprise_id", userdata.getEnterpriseId());
        List<MyCompanyEnterprise> myCompanyEnterprises = serviceHelper.getMyCompanyEnterpriseMapper().selectByMap(paramMap);
        if (!CollectionUtils.isEmpty(myCompanyEnterprises)) {
            return;
        }
        //添加关联
        MyCompanyEnterprise myCompanyEnterprise = new MyCompanyEnterprise();
        myCompanyEnterprise.setMyCompanyId(myCompanyId);
        myCompanyEnterprise.setEnterpriseId(enterpriseId);
        myCompanyEnterprise.setMainCompany(MyCompanyEnterpriseEnum.ACCORD_WITH.getCode());
        myCompanyEnterprise.setState(AuditStatusEnum.APPROVE.getErpStatusCode());
        myCompanyEnterprise.setCreateDate(new Date());
        serviceHelper.getMyCompanyEnterpriseMapper().insert(myCompanyEnterprise);
    }

    @Override
    public void updateMyCompanyExternalId(ErpMyCompanyNameVo erpMyCompanyNameVo) {
        if (!StringUtils.validateParameter(erpMyCompanyNameVo.getName())) {
            return;
        }
        UpdateWrapper<MyCompany> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("name", erpMyCompanyNameVo.getName());
        updateWrapper.set("enterprise_id", erpMyCompanyNameVo.getID());
        updateWrapper.set("country_region_id", erpMyCompanyNameVo.getDistrict());
        updateWrapper.set("company_type_id", erpMyCompanyNameVo.getSupplierType());
        updateWrapper.set("invoic_type_id", erpMyCompanyNameVo.getInvoiceType());
        updateWrapper.set("erp_receive", 1);
        //查询币种
        //判断国别,非国内才需要更新
        MyCompanyCurrency myCompanyCurrency = myCompanyCurrencyService.findByName(erpMyCompanyNameVo.getCurrency());
        if (myCompanyCurrency != null) {
            updateWrapper.set("currency_id", myCompanyCurrency.getId());
        }
        //查询国家
/*        if (StringUtils.validateParameter(erpMyCompanyNameVo.getPlace())) {
            List<String> paramList = new ArrayList<>();
            paramList.add(MyCompanyDictionariesEnum.COUNTRY_OF_ORIGIN.getcName());
            List<Dictionaries> dictionariesList = dictionariesService.findByDcodes(paramList);
            for (Dictionaries dictionaries : dictionariesList) {
                if (dictionaries.getDValue().equals(erpMyCompanyNameVo.getPlace())) {
                    updateWrapper.set("country_id", dictionaries.getId());
                }
            }
        }*/
        update(updateWrapper);
        //重新更新缓存
      /*  MyCompany myCompany = this.baseMapper.findByEnterpriseId(erpMyCompanyNameVo.getID());
        if (myCompany == null) {
            return;
        }
        this.initMyCompanyService.savaRedistMyCompany(myCompany);*/
    }

    @Override
    public MyCompany findByName(String name) {
        return this.baseMapper.findByName(name);
    }

    @Override
    public List<MyCompany> findByMyCompanyList(SearchCompanyVo searchCompanyVo) {
        PageHelper.startPage(searchCompanyVo.getPage(), searchCompanyVo.getPageSize());
        return this.baseMapper.findByMyCompanyList(searchCompanyVo);
    }

 /*   @Override
    public ServiceResult<MyCompanyPojo> getRedisDetail(Integer id) {
        ServiceResult<MyCompanyPojo> serviceResult = new ServiceResult<>();
        Object object = serviceHelper.getRedisManager().get(RedisKeyPrefixEnum.MY_COMPANY_GET_DETAIL.getCode() + "_" + id);
        if (object == null) {
            return serviceResult;
        }
        return JSON.parseObject(object.toString(), ServiceResult.class);
    }*/


    @Override
    public ServiceResult<MyCompanyPojo> getRedisDetail(Integer relationEnterpriseId) {
        //查找关联
        MyCompanyEnterprise myCompanyEnterprise = serviceHelper.getMyCompanyEnterpriseMapper().selectById(relationEnterpriseId);
        MyCompany myCompany = this.baseMapper.selectById(myCompanyEnterprise.getMyCompanyId());
        MyCompanyPojo myCompanyPojo = new MyCompanyPojo();
        //copy对象
        BeanUtil.copyProperties(myCompany, myCompanyPojo);
        myCompanyPojo.setId(myCompany.getId());
        myCompanyPojo.setName(myCompany.getName());

        Dictionaries countryRegionDictionaries = dictionariesService.findByDictionariesId(myCompany.getCountryRegionId());


        myCompanyPojo.setCountryRegion(myCompany.getCountryRegionId());
        if (countryRegionDictionaries != null) {
            myCompanyPojo.setCountryRegionName(countryRegionDictionaries.getDName());
        }

        Dictionaries companyType = dictionariesService.findByDictionariesId(myCompany.getCompanyTypeId());
        myCompanyPojo.setCompanyType(myCompany.getCompanyTypeId());
        if (companyType != null) {
            myCompanyPojo.setCompanyTypeName(DictionariesAlias.of(companyType.getDName()).getTarget());
        }

        Dictionaries invoicTyp = dictionariesService.findByDictionariesId(myCompany.getInvoicTypeId());
        myCompanyPojo.setInvoicType(myCompany.getInvoicTypeId());
        if (invoicTyp != null) {
            myCompanyPojo.setInvoicTypeName(invoicTyp.getDName());
        }

        MyCompanyCurrency myCompanyCurrency = myCompanyCurrencyService.findById(myCompany.getCurrencyId());
        if (myCompanyCurrency != null) {
            myCompanyPojo.setCurrencyName(myCompanyCurrency.getName());
        }

        //查找附件集合
        ServiceResult<List<UploadFile>> uploadFileResult = uploadFileService.findByRelationId(UploadFileEnum.MY_COMPANY, relationEnterpriseId + "");
        if (!CollectionUtils.isEmpty(uploadFileResult.getResult())) {
            List<UploadFile> uploadFile = uploadFileResult.getResult();
            List<UploadFilePojo> uploadFilePojoList = new ArrayList<>();
            for (UploadFile file : uploadFile) {
                UploadFilePojo uploadFilePojo = new UploadFilePojo();
                uploadFilePojo.setFileName(file.getFileName());
                uploadFilePojo.setFullPath(file.getFullPath());
                uploadFilePojo.setCustomType(file.getCustomType());
                uploadFilePojo.setId(file.getId());
                uploadFilePojoList.add(uploadFilePojo);
            }
            //包装result
            myCompanyPojo.setFiles(uploadFilePojoList);
        }
        List<MyCompanyCollectionInformationPojo> myCompanyCollectionInformationPojos = new ArrayList<>();
        MyCompanyCollectionInformationPojo myCompanyCollectionInformationPojo = new MyCompanyCollectionInformationPojo();
        myCompanyCollectionInformationPojo.setId(myCompany.getId());
        myCompanyCollectionInformationPojo.setCurrency(myCompanyPojo.getCurrencyName());
        myCompanyCollectionInformationPojo.setReceivingCompany(myCompanyPojo.getReceivingCompany());
        myCompanyCollectionInformationPojo.setBankOfDeposit(myCompanyPojo.getBankOfDeposit());
        myCompanyCollectionInformationPojo.setAccountNumber(myCompanyPojo.getAccountNumber());
        myCompanyCollectionInformationPojo.setBankAddress(myCompanyPojo.getBankAddress());
        myCompanyCollectionInformationPojo.setSwiftCode(myCompanyPojo.getSwiftCode());
        myCompanyCollectionInformationPojo.setTransitBank(myCompanyPojo.getTransitBank());
        myCompanyCollectionInformationPojos.add(myCompanyCollectionInformationPojo);
        myCompanyPojo.setMyCompanyCollectionInformationPojo(myCompanyCollectionInformationPojos);
        ServiceResult<MyCompanyPojo> serviceResult = new ServiceResult<>();
        serviceResult.setResult(myCompanyPojo);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }


    /**
     * 发送注册消息
     *
     * @param myCompanyVo
     */
    private void sendRegisterCompany(MyCompanyVo myCompanyVo) throws IOException {
        //组装 RegisterMyCompanyPojo
        RegisterMyCompanyPojo registerMyCompanyPojo = new RegisterMyCompanyPojo();
        //主账号公司id
        registerMyCompanyPojo.setEnterpriseID(myCompanyVo.getEnterpriseId());
        registerMyCompanyPojo.setName(myCompanyVo.getName());
        //国别地区,id
        registerMyCompanyPojo.setDistrict(myCompanyVo.getCountryRegionId());

        //供应商类型
        ServiceResult<Dictionaries> supplierTypeServiceResult = dictionariesService.findById(myCompanyVo.getCompanyTypeId());
        if (supplierTypeServiceResult != null && supplierTypeServiceResult.getResult() != null) {
            registerMyCompanyPojo.setSupplierType(supplierTypeServiceResult.getResult().getDValue());
        }


        //发票类型
        ServiceResult<Dictionaries> invoicTypeServiceResult = dictionariesService.findById(myCompanyVo.getInvoicTypeId());
        if (invoicTypeServiceResult != null && invoicTypeServiceResult.getResult() != null) {
            registerMyCompanyPojo.setInvoiceType(Integer.valueOf(invoicTypeServiceResult.getResult().getDValue()));
        }

        Map<String, MyCompanyCurrency> currencyMap = new HashMap<>();
        List<MyCompanyCurrency> myCompanyCurrencyList = myCompanyCurrencyService.findAll();
        for (MyCompanyCurrency myCompanyCurrency : myCompanyCurrencyList) {
            currencyMap.put(myCompanyCurrency.getId() + "", myCompanyCurrency);
        }

        MyCompanyCurrency myCompanyCurrency = currencyMap.get(myCompanyVo.getCurrencyId());
        if (myCompanyCurrency != null) {
            registerMyCompanyPojo.setCurrency(myCompanyCurrency.getExternalId());
        }


        registerMyCompanyPojo.setTitle(myCompanyVo.getName());
        registerMyCompanyPojo.setBank(myCompanyVo.getBankOfDeposit());
        registerMyCompanyPojo.setAccount(myCompanyVo.getAccountNumber());
        registerMyCompanyPojo.setBankAddress(myCompanyVo.getBankAddress());
        registerMyCompanyPojo.setSwiftCode(myCompanyVo.getSwiftCode());
        registerMyCompanyPojo.setTransfer(myCompanyVo.getTransitBank());
        registerMyCompanyPojo.setCreator(myCompanyVo.getCreatorUserName());
        //组装文件
        List<UploadFileMessagePojo> uploadFileMessagePojoList = new ArrayList<>();
        ServiceResult<List<UploadFile>> uploadFileResult = uploadFileService.findByRelationId(UploadFileEnum.MY_COMPANY, myCompanyVo.getId() + "");
        if (uploadFileResult != null && !CollectionUtils.isEmpty(uploadFileResult.getResult())) {
            List<UploadFile> uploadFileList = uploadFileResult.getResult();
            for (UploadFile uploadFile : uploadFileList) {
                UploadFileMessagePojo uploadFileMessagePojo = new UploadFileMessagePojo();
                uploadFileMessagePojo.setFileName(uploadFile.getFileName());
                uploadFileMessagePojo.setUrl(uploadFile.getFullPath());
                uploadFileMessagePojoList.add(uploadFileMessagePojo);
            }
            registerMyCompanyPojo.setFiles(uploadFileMessagePojoList);

        }

        JSONObject json = (JSONObject) JSONObject.toJSON(registerMyCompanyPojo);
        // 包装发送到rabbitmq的消息内容
        JSONObject result = serviceHelper.packageSendRabbitMqMsgData(json, RabbitMqConstants.SC_ERP_REGISTER_COMPANY);
        log.info("推送给rabbitmq注册我的公司消息,交换机:[{}],队列:[{}] , key:[{}] ,的消息内容为:[{}]  ", RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_TO_ERP_CRM_QUEUE_NAME, RabbitMqConstants.SC_ERP_REGISTER_COMPANY, result.toString());
        serviceHelper.getRabbitMqManager().basicPublish(RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_TO_ERP_CRM_QUEUE_NAME, RabbitMqConstants.SC_ERP_REGISTER_COMPANY, null, result.toString().getBytes());
    }

    /**
     * 根据creator_id查找我的公司名称列表
     *
     * @param epId
     * @return
     */
    @Override
    public ServiceResult<List<String>> findByEpId(String epId) {
        ServiceResult<List<String>> serviceResult = new ServiceResult<>();
        List<String> myCompanyNameList = serviceHelper.getMyCompanyMapper().findByEpId(epId);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setResult(myCompanyNameList);
        return serviceResult;
    }

    @Override
    public void ListenAddCompanyBookaccount(ErpBookAccountVo erpBookAccountVo) {
        UpdateWrapper<MyCompany> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("enterprise_id", erpBookAccountVo.getEnterpriseID());
        updateWrapper.set("book_account_id", erpBookAccountVo.getID());
        updateWrapper.set("receiving_company", erpBookAccountVo.getTitle());
        updateWrapper.set("bank_of_deposit", erpBookAccountVo.getBank());
        updateWrapper.set("account_number", erpBookAccountVo.getAccount());
        updateWrapper.set("bank_address", erpBookAccountVo.getBankAddress());
        updateWrapper.set("swift_code", erpBookAccountVo.getSwiftCode());
        updateWrapper.set("swift_code", erpBookAccountVo.getSwiftCode());
        updateWrapper.set("transit_bank", erpBookAccountVo.getTransfer());
        //转换币种
        String currency = erpBookAccountVo.getCurrency();
        MyCompanyCurrency myCompanyCurrency = myCompanyCurrencyService.findByExternalId(currency);
        if (myCompanyCurrency != null) {
            updateWrapper.set("currency_id", myCompanyCurrency.getId());
        }
        this.baseMapper.update(null, updateWrapper);
        MyCompany myCompany = this.baseMapper.findByEnterpriseId(erpBookAccountVo.getEnterpriseID());
        if (myCompany == null) {
            return;
        }
        initMyCompanyService.savaRedistMyCompany(myCompany);
    }

    @Override
    public ServiceResult updateBookAccount(MyCompanyVo myCompanyVo) throws IOException {
        ServiceResult serviceResult = new ServiceResult();
        UpdateWrapper<MyCompany> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", myCompanyVo.getId());
        //币种
        MyCompanyCurrency myCompanyCurrency = myCompanyCurrencyService.findByName(myCompanyVo.getCurrencyId());
        if (myCompanyCurrency != null) {
            updateWrapper.set("currency_id", myCompanyCurrency.getExternalId());
        } else {
            //尝试用值去转换
            MyCompanyCurrency findByCompanyCurrency = myCompanyCurrencyService.findById(myCompanyVo.getCurrencyId());
            if (findByCompanyCurrency != null) {
                updateWrapper.set("currency_id", findByCompanyCurrency.getExternalId());
            }
        }
        //收款公司
        updateWrapper.set("receiving_company", myCompanyVo.getReceivingCompany());
        //开户银行
        updateWrapper.set("bank_of_deposit", myCompanyVo.getBankOfDeposit());
        //账号
        updateWrapper.set("account_number", myCompanyVo.getAccountNumber());
        //银行地址
        updateWrapper.set("bank_address", myCompanyVo.getBankAddress());
        updateWrapper.set("swift_code", myCompanyVo.getSwiftCode());
        //中转银行
        updateWrapper.set("transit_bank", myCompanyVo.getTransitBank());
        this.baseMapper.update(null, updateWrapper);
        //发送消息队列给erp
        MyCompany myCompany = this.baseMapper.selectById(myCompanyVo.getId());
        this.sendUpdateBookAccountMessage(myCompanyVo, myCompany);
        initMyCompanyService.savaRedistMyCompany(myCompany);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        return serviceResult;
    }

    @Override
    public void ListenAddBookaccountSuccess(ErpBookAccountVo erpBookAccountVo) {
        if (!StringUtils.validateParameter(erpBookAccountVo.getEnterpriseID()) || !StringUtils.validateParameter(erpBookAccountVo.getID())) {
            return;
        }
        UpdateWrapper<MyCompany> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("enterprise_id", erpBookAccountVo.getEnterpriseID());
        //付款id
        updateWrapper.set("book_account_id", erpBookAccountVo.getID());
        this.baseMapper.update(null, updateWrapper);
    }

    @Override
    public void ListenAddBookaccountClose(ErpBookAccountVo erpBookAccountVo) {
        UpdateWrapper<MyCompany> updateWrapper = new UpdateWrapper<>();
        if (!StringUtils.validateParameter(erpBookAccountVo.getEnterpriseID())) {
            return;
        }
        updateWrapper.eq("enterprise_id", erpBookAccountVo.getEnterpriseID());
        //币种
        updateWrapper.set("currency_id", null);
        //收款公司
        updateWrapper.set("receiving_company", null);
        //开户银行
        updateWrapper.set("bank_of_deposit", null);
        //账号
        updateWrapper.set("account_number", null);
        //银行地址
        updateWrapper.set("bank_address", null);
        updateWrapper.set("swift_code", null);
        //中转银行
        updateWrapper.set("transit_bank", null);
        this.baseMapper.update(null, updateWrapper);
        MyCompany myCompany = this.baseMapper.findByEnterpriseId(erpBookAccountVo.getEnterpriseID());
        if (myCompany == null) {
            return;
        }
        initMyCompanyService.savaRedistMyCompany(myCompany);
    }


    @Override
    public ServiceResult updateMyCompany(MyCompanyVo myCompanyVo) throws IOException {
        ServiceResult serviceResult = new ServiceResult();
        MyCompany myCompany = this.baseMapper.selectById(myCompanyVo.getId());

        UpdateWrapper<MyCompany> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", myCompanyVo.getId());
        //国别地区
        updateWrapper.set("country_region_id", myCompanyVo.getCountryRegionId());
        //公司类型
        updateWrapper.set("company_type_id", myCompanyVo.getCompanyTypeId());
        //发票类型
        updateWrapper.set("invoic_type_id", myCompanyVo.getInvoicTypeId());
        updateWrapper.set("erp_receive", 0);
        MyCompanyCurrency myCompanyCurrency = myCompanyCurrencyService.findByName(myCompanyVo.getCurrencyId());
        if (myCompanyCurrency != null) {
            myCompany.setCurrencyId(myCompanyCurrency.getId().toString());
            updateWrapper.set("currency_id", myCompanyCurrency.getId().toString());
        }
        this.baseMapper.update(null, updateWrapper);
        //查看是否有图片
        //保存图片
        List<UploadFileVo> uploadFileVo = myCompanyVo.getUploadFileVo();
        if (!CollectionUtils.isEmpty(uploadFileVo)) {
            for (UploadFileVo fileVo : uploadFileVo) {
                uploadFileService.updateRelationIdAndType(fileVo.getId().toString(), UploadFileEnum.MY_COMPANY, myCompany.getId(), fileVo.getCustomType());
            }
        }
        myCompanyVo.setEnterpriseId(myCompany.getEnterpriseId());
        myCompanyVo.setName(myCompany.getName());
        //推送mq
        this.sendUpdateCompany(myCompanyVo);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(myCompanyVo);
        return serviceResult;
    }


    /**
     * 发送给erp收款信息消息
     *
     * @param myCompanyVo
     */
    private void sendUpdateBookAccountMessage(MyCompanyVo myCompanyVo, MyCompany myCompany) throws IOException {
        ErpBookAccountVo erpBookAccountVo = new ErpBookAccountVo();
        erpBookAccountVo.setID(myCompany.getBookAccountId());
        erpBookAccountVo.setEnterpriseID(myCompany.getEnterpriseId());
        erpBookAccountVo.setTitle(myCompanyVo.getReceivingCompany());
        erpBookAccountVo.setBank(myCompanyVo.getBankOfDeposit());
        erpBookAccountVo.setAccount(myCompanyVo.getAccountNumber());
        erpBookAccountVo.setBankAddress(myCompanyVo.getBankAddress());
        erpBookAccountVo.setSwiftCode(myCompanyVo.getSwiftCode());
        erpBookAccountVo.setTransfer(myCompanyVo.getTransitBank());
        //发送的时候 转换币种
        String currencyId = myCompanyVo.getCurrencyId();
        MyCompanyCurrency myCompanyCurrency = myCompanyCurrencyService.findById(currencyId);
        if (myCompanyCurrency != null) {
            erpBookAccountVo.setCurrency(myCompanyCurrency.getExternalId());
        } else {
            //尝试用值去转换
            MyCompanyCurrency findByCompanyCurrency = myCompanyCurrencyService.findById(myCompanyVo.getCurrencyId());
            if (findByCompanyCurrency != null) {
                erpBookAccountVo.setCurrency(findByCompanyCurrency.getExternalId());
            }
        }
        JSONObject json = (JSONObject) JSONObject.toJSON(erpBookAccountVo);
        // 包装发送到rabbitmq的消息内容
        JSONObject result = serviceHelper.packageSendRabbitMqMsgData(json, RabbitMqConstants.SC_ERP_CURRENCY_UPDATE);
        log.info("推送给rabbitmq我的公司-付款账户修改-消息,交换机:[{}],队列:[{}] , key:[{}] ,的消息内容为:[{}]  ", RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_TO_ERP_CRM_QUEUE_NAME, RabbitMqConstants.SC_ERP_CURRENCY_UPDATE, result.toString());
        serviceHelper.getRabbitMqManager().basicPublish(RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_TO_ERP_CRM_QUEUE_NAME, RabbitMqConstants.SC_ERP_CURRENCY_UPDATE, null, result.toString().getBytes());
    }


    /**
     * 发送更新公司消息
     *
     * @param myCompanyVo
     */
    private void sendUpdateCompany(MyCompanyVo myCompanyVo) throws IOException {
        //组装 RegisterMyCompanyPojo
        RegisterMyCompanyPojo registerMyCompanyPojo = new RegisterMyCompanyPojo();
        //主账号公司id
        registerMyCompanyPojo.setEnterpriseID(myCompanyVo.getEnterpriseId());
        registerMyCompanyPojo.setName(myCompanyVo.getName());
        //国别地区,id
        registerMyCompanyPojo.setDistrict(myCompanyVo.getCountryRegionId());

        //供应商类型
        ServiceResult<Dictionaries> supplierTypeServiceResult = dictionariesService.findById(myCompanyVo.getCompanyTypeId());
        if (supplierTypeServiceResult != null && supplierTypeServiceResult.getResult() != null) {
            registerMyCompanyPojo.setSupplierType(supplierTypeServiceResult.getResult().getDValue());
        }
        //发票类型
        ServiceResult<Dictionaries> invoicTypeServiceResult = dictionariesService.findById(myCompanyVo.getInvoicTypeId());
        if (invoicTypeServiceResult != null && invoicTypeServiceResult.getResult() != null) {
            registerMyCompanyPojo.setInvoiceType(Integer.valueOf(invoicTypeServiceResult.getResult().getDValue()));
        }
        //组装文件
        List<UploadFileMessagePojo> uploadFileMessagePojoList = new ArrayList<>();
        ServiceResult<List<UploadFile>> uploadFileResult = uploadFileService.findByRelationId(UploadFileEnum.MY_COMPANY, myCompanyVo.getId() + "");
        if (uploadFileResult != null && !CollectionUtils.isEmpty(uploadFileResult.getResult())) {
            List<UploadFile> uploadFileList = uploadFileResult.getResult();
            for (UploadFile uploadFile : uploadFileList) {
                UploadFileMessagePojo uploadFileMessagePojo = new UploadFileMessagePojo();
                uploadFileMessagePojo.setFileName(uploadFile.getFileName());
                uploadFileMessagePojo.setUrl(uploadFile.getFullPath());
                uploadFileMessagePojoList.add(uploadFileMessagePojo);
            }
            registerMyCompanyPojo.setFiles(uploadFileMessagePojoList);
        }
        JSONObject json = (JSONObject) JSONObject.toJSON(registerMyCompanyPojo);
        // 包装发送到rabbitmq的消息内容
        JSONObject result = serviceHelper.packageSendRabbitMqMsgData(json, RabbitMqConstants.SC_ERP_REGISTER_COMPANY);
        log.info("推送给rabbitmq注册我的公司消息,交换机:[{}],队列:[{}] , key:[{}] ,的消息内容为:[{}]  ", RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_TO_ERP_CRM_QUEUE_NAME, RabbitMqConstants.SC_ERP_UPDATE_COMPANY, result.toString());
        serviceHelper.getRabbitMqManager().basicPublish(RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_TO_ERP_CRM_QUEUE_NAME, RabbitMqConstants.SC_ERP_UPDATE_COMPANY, null, result.toString().getBytes());
    }


    private String downloadPicture(String url, String fileName) {
        if (!StringUtils.validateParameter(url)) {
            return null;
        }
        String finalUrl = url;
        if (!url.startsWith(Constants.HTTPS)) {
            finalUrl = Constants.HTTPS + url;
        }
        //后缀名字
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        //生成唯一文件名
        String onlyFileName = IdUtil.simpleUUID() + "." + suffix;
        byte[] bytes = null;
        try {
            bytes = HttpUtils.downloadPicture(finalUrl);
        } catch (IOException e) {
            log.error("下载图片发生错误", e);
            return null;
        }
        //上传文件
        serviceHelper.getSftpChannelManager().upload(serviceHelper.getFileParamConfig().getFileUrl(), bytes, onlyFileName);
        return serviceHelper.getFileParamConfig().getImageExhibitionUrl() + onlyFileName;
    }


}